SpringBoot官方文档翻译(十四):组织你的代码

14. Structuring Your Code(组织您的代码)

1
2
Spring Boot does not require any specific code layout to work.     
However, there are some best practices that help.

Spring Boot不需要任何特殊的代码框架就能运行。然而,有一些最佳实践可以给予您更多的帮助。

14.1 Using the “default” Package(使用默认包)

1
2
3
4
5
6
When a class does not include a package declaration, it is     
considered to be in the “default package”. The use of the
“default package” is generally discouraged and should be
avoided. It can cause particular problems for Spring Boot
applications that use the @ComponentScan, @EntityScan, or @SpringBootApplicationannotations, since every class
from every jar is read.

当一个类不包含包声明时,它是被认为是在“默认包”中。 使用“默认包”通常是不鼓励的,应该是
避免。 它可能会导致Spring Boot的特殊问题,诸如在使用@ComponentScan,@EntityScan或@SpringBootApplicationannotations的应用程序,因为每个包里的每个类都会被读取。

1
2
3
We recommend that you follow Java’s recommended package naming     
conventions and use a reversed domain name (for example, 
com.example.project).

我们建议您遵循Java推荐的软件包命名约定并使用反向域名(例如,com.example.project)。

14.2 Locating the Main Application Class(定位主应用类)

1
2
3
4
5
6
7
We generally recommend that you locate your main application     
class in a root package above other classes .The @SpringBootApplication annotation is often placed
on your main class, and it implicitly defines a base “search
package” for certain items. For example, if you are writing a
JPA application, the package of the @SpringBootApplication annotated
class is used to search for @Entity items. Using a root package also
allows component scan to apply only on your project.

我们通常推荐您将主应用类放到高于其他的类的根目录。@SpringBootApplication注解一般用于您的主应用类上,它隐含地为某些项目定义了一个基础“搜索包”。举个例子,如果你正在写一个JPA应用程序,@SpringBootApplication注释类所在的包将会用于搜索@Entity注解。 使用根包也允许组件扫描仅适用于您的项目。

1
2
3
4
If you don’t want to use @SpringBootApplication,     
the @EnableAutoConfiguration and @ComponentScan 
annotations that it imports defines that behaviour
so you can also use that instead.

如果您不想使用注解@SpringBootApplication,注解@EnableAutoConfiguration@ComponentScan组合使用可以起到替代它的作用。

1
The following listing shows a typical layout:

以下的列表显示了一个典型的类和包结构布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
com
+- example
+- myapplication
+- Application.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java

1
2
The Application.java file would declare the main method,     
along with the basic @SpringBootApplication, as follows:

Application.java文件将定义main方法,已经基本的@SpringBootApplication如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

分享到